<?php

namespace app\mini\controller\salesman;

use app\common\controller\ApiController;
use app\common\enum\order\GoodsType;
use app\common\model\CompanyWarehouse;
use app\common\model\DealerGoods;
use app\common\traits\SearchTrait;
use app\company\model\CompanyWarehouseGoods;
use app\mini\model\Cart;
use think\App;
use think\response\Json;

class Search extends ApiController
{
    use SearchTrait;

    protected array  $get    = [];
    protected string $fields = '*';

    public function __construct(App $app)
    {
        parent::__construct($app);
        // 传递参数，字段严格按照数据库字段标准查询，特定字段需要特定处理
        $this->get = $this->request->get();
        // 搜索字段
        $this->fields = !empty($this->get['fields']) ? htmlspecialchars_decode($this->get['fields']) : '*';
    }

    /**
     * 商品列表
     */
    public function warehouseGoodsList(): Json
    {
        $rule = [
                'page|页码'         => 'require',
                'limit|条数'        => 'require',
                'warehouse_id|仓库' => 'require',
                'store_id|门店'     => 'require',
        ];
        $this->validate($this->get, $rule);
        $sql     = $this->model = new CompanyWarehouseGoods();
        $where   = [];
        $where[] = ['warehouse_id', '=', $this->get['warehouse_id']];
        if (!empty($this->get['name'])) {
            $goodsIds = (new DealerGoods())->where('name', 'like', '%' . $this->get['name'] . '%')
                                           ->column('id');
            $where[]  = ['dealer_goods_id', 'in', $goodsIds];
        }
        if (!empty($this->get['cate_id'])) {
            $goodsIds = (new DealerGoods())->where('cate_id', $this->get['cate_id'])->column('id');
            $where[]  = ['dealer_goods_id', 'in', $goodsIds];
        }
        $where[] = ['company_id', '=', $this->companyId];
        $data = [];
        $list    = $sql->where($where)
                       ->paginate($this->get['limit'])
                       ->each(function ($item) use (&$data)
                       {
                           $goods = $item->goods()->withTrashed()->find();
                           $goods->spec = $goods->spec()->select();
                           // 查询购物车是否存在商品，获取已经添加数量
                           if($this->get['type'] == 1){
                               $where[] = ['goods_type', 'in', [1,2]];
                           }else{
                               $where[] = ['goods_type', '=', 3];
                           }
                           $cartList = Cart::field('num,unit,goods_type,dealer_goods_spec_id,remark')
                                           ->where('store_id', $this->get['store_id'])
                                           ->where('salesman_id',$this->uid)
                                           ->where('company_warehouse_id', $this->get['warehouse_id'])
                                           ->where($where)
                                           ->where('dealer_goods_id',$item->dealer_goods_id)
                                           ->order('goods_type asc')
                                           ->select();
                           if($this->get['type'] == 1){
                               $desc = '';
                               foreach ($cartList as $cart){
                                   if ($cart['goods_type'] == GoodsType::GIFT){
                                       $desc .= '赠'.$cart['num'].$cart['unit'].',';
                                   }else{
                                       $desc .= $cart['num'].$cart['unit'].',';
                                   }
                               }
                           }else{
                               $desc = '退';
                               foreach ($cartList as $cart){
                                   $desc .= $cart['num'].$cart['unit'].',';
                               }
                           }
                           $desc = rtrim($desc,',');
                           $specArr = $goods['spec']->toArray();
                           $goods->spec_name = implode(',',array_column($specArr,'name'));
                           $specPrice = '';
                           array_multisort(array_column($specArr,'sale_price'),SORT_ASC,$specArr);
                           foreach ($specArr as $spec){
                               $specPrice .= '￥'.$spec['sale_price'].',';
                           }
                           $specPrice = rtrim($specPrice,',');
                           usort($specArr, function ($a, $b) {
                               return $b['ratio'] <=> $a['ratio'];  // 使用太空船操作符进行升序排序
                           });
                           $sales_stock = $item->stock;
                           $stockArray = [];
                           foreach ($specArr as $spec){
                               $stockArray[$spec['id']] = intdiv($sales_stock,$spec['ratio']);
                               $sales_stock = $sales_stock % $spec['ratio'];
                           }
                           $goods->cart_desc = $desc;
                           $goods->spec_price = $specPrice;
                           $goods->spec->each(function ($spec) use ($stockArray){
                               $spec->stock = $stockArray[$spec->id];
                               $spec->remark = Cart::where('store_id',$this->get['store_id'])
                                                   ->where('salesman_id',$this->uid)
                                                   ->where('dealer_goods_spec_id',$spec->id)
                                                   ->value('remark')??'';
                           });
                           $data[] = $goods;
                       })->toArray();
        $list['data'] = $data;
        return $this->success($list);
    }
}